package com.ruoyi.dataserver.point.service.impl;

import com.ruoyi.dataserver.point.dto.PointFieldAndOperationSymbolAndValue;
import com.ruoyi.dataserver.point.entity.Point;
import com.ruoyi.dataserver.point.dto.LayerAndPointFieldAndOperationSymbolAndValue;
import com.ruoyi.dataserver.point.service.PointService;
import com.ruoyi.dataserver.point.utils.PointSqlUtil;
import com.ruoyi.dataserver.service.ISearchTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @ProjectName intelligent-city
 * @Package com.ruoyi.point.service.impl
 * @ClassName PointServiceImpl
 * @Description 附属物
 * @Company lab
 * @Author zgq
 * @Date 2020/7/14 13:53
 * @UpdateUser
 * @UpdateDate
 * @UpdateRemark
 * @Version 1.0.0
 */
@Service
public class PointServiceImpl implements PointService {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    public ISearchTableService tableService;

    @Override
    public List<Point> select(List<LayerAndPointFieldAndOperationSymbolAndValue> lpovList) {
        List<Point> result = new ArrayList();
        List<Point> queryList = new ArrayList<>();
        //为了减少访问数据库的次数,将参数按照图层进行分组,根据图层来查询
        Map<String, List<LayerAndPointFieldAndOperationSymbolAndValue>> mapByLayer = lpovList.stream().collect(Collectors.groupingBy(LayerAndPointFieldAndOperationSymbolAndValue::getLayer));
        mapByLayer.forEach((layer, lpvos) -> {
            List<PointFieldAndOperationSymbolAndValue> povList = lpvos.stream()
                    .map(lpvo -> new PointFieldAndOperationSymbolAndValue(lpvo.getPointField(), lpvo.getOperationSymbol(), lpvo.getValue()))
                    .collect(Collectors.toList());
            RowMapper<Point> rowMapper = new BeanPropertyRowMapper<Point>(Point.class);
            List<Point> query = jdbcTemplate.query(PointSqlUtil.selectSql(tableService.searchPointTable(layer), povList), rowMapper);
            queryList.addAll(query);
        });
        //这里从查询出来的数据,根据传入参数顺序进行排序
        lpovList.forEach(lpov -> {
            Optional<Point> first = queryList.stream().filter(query -> query.getDm().equals(lpov.getLayer()) && query.getWtdh().equals(lpov.getValue())).findFirst();
            if (first.isPresent()){
                result.add(first.get());
            }
        });
        return result;
    }
}
